package com.jh.fcsm.util;

import com.jh.fcsm.beans.sys.vo.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class AppUserUtil {

    /**
     * 获取登陆的 LoginAppUser
     *
     * @return
     */
    public static Object getLoginAppUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
            if (authenticationToken.getPrincipal() instanceof LoginUser) {
                LoginUser loginuser = (LoginUser) authenticationToken.getPrincipal();
                loginuser.setPassword(null);
                return loginuser;
            }
        }
        return null;
    }

    public static String getCurrentUserId() {
        Object user = getLoginAppUser();
        if (user instanceof LoginUser) {
            LoginUser appLoginUser = (LoginUser) user;
            return appLoginUser.getId();
        }
        return null;
    }

    public static String getCurrentUserName() {
        Object user = getLoginAppUser();
        if (user instanceof LoginUser) {
            LoginUser appLoginUser = (LoginUser) user;
            return appLoginUser.getUsername();
        }
        return null;
    }

    public static String getCurrentRealName() {
        Object user = getLoginAppUser();
        if (user instanceof LoginUser) {
            LoginUser appLoginUser = (LoginUser) user;
            return appLoginUser.getNickname();
        }
        return null;
    }

}
